import $ from './lib/jquery.esm.js';
import cookie from './lib/cookie.js';

let id = location.search.split('=')[1];
console.log(id);

$.ajax({
  type: "get",
  url: "../interface/getitem.php",
  data: { id },
  dataType: "json"
}).then(res => {
  let pic = JSON.parse(res.picture);

  

  let template = `
  <div class="title">${res.title}</div>
  <div class="price">价格:<span style="color:red;">${res.price}<span></div>
  `;

  let template2 = `
  <div>
    <img src="./${pic[5][0].src}">
  </div>
  <div>
    <img src="./${pic[5][1].src}">
  </div>
  <div>
    <img src="./${pic[5][2].src}">
  </div>
  <div>
    <img src="./${pic[5][3].src}">
  </div>
  <div>
    <img src="./${pic[5][4].src}">
  </div>
  <div>
    <img src="./${pic[5][5].src}">
  </div>
  <div>
    <img src="./${pic[5][6].src}">
  </div>
  <div>
    <img src="./${pic[5][7].src}">
  </div>
  <div>
    <img src="./${pic[5][8].src}">
  </div>
  <div>
    <img src="./${pic[5][9].src}">
  </div>
  <div>
    <img src="./${pic[5][10].src}">
  </div>
  <div>
    <img src="./${pic[5][11].src}">
  </div>
  <div>
    <img src="./${pic[5][12].src}">
  </div>
  <div>
    <img src="./${pic[5][13].src}" style="width:790px;">
  </div>

  `;

  $('.theme-cen-top').html(template);
  $('.content-cen-picture').html(template2);

  $('#additem').on('click',function(){
    addItem(res.id,$('#num').val());
  });
}).catch(xhr => {
  console.log(xhr.status);
});

function addItem(id,num){
  let product = {id,num};

  let shop = cookie.get('shop');

  if(shop){
    shop = JSON.parse(shop);

    if(shop.some(el=>el.id == id)){
      let index = shop.findIndex(elm=>elm.id == id);
      let count = parseInt(shop[index].num);
      count += parseInt(num);
      shop[index].num = count;
    }else{
      shop.push(product);
    }

  }else{
    shop=[];
    shop.push(product);
  }

  cookie.set('shop',JSON.stringify(shop));
}
